﻿package com.rbac.system.service.impl;

import com.rbac.system.common.Result;
import com.rbac.system.entity.Permission;
import com.rbac.system.entity.RolePermission;
import com.rbac.system.mapper.PermissionMapper;
import com.rbac.system.mapper.RolePermissionMapper;
import com.rbac.system.service.PermissionDependencyService;
import com.rbac.system.service.PermissionSyncService;
import com.rbac.system.service.RolePermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class RolePermissionServiceImpl implements RolePermissionService {

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private PermissionDependencyService permissionDependencyService;

    @Autowired
    private PermissionSyncService permissionSyncService;

    @Override
    @Transactional
    public Result<String> assignPermissionsToRole(Long roleId, List<Long> permissionIds) {
        try {
            // 先删除该角色的所有权限
            rolePermissionMapper.deleteByRoleId(roleId);

            // 如果权限ID列表不为空，则新增权限关联
            if (permissionIds != null && !permissionIds.isEmpty()) {
                // 解析权限依赖，获取完整的权限列表（包括父级权限）
                Set<Long> allPermissionIds = permissionDependencyService.resolvePermissionDependencies(permissionIds);

                // 为每个权限创建角色权限关联
                for (Long permissionId : allPermissionIds) {
                    RolePermission rolePermission = new RolePermission();
                    rolePermission.setRoleId(roleId);
                    rolePermission.setPermissionId(permissionId);
                    rolePermission.setCreateTime(LocalDateTime.now());
                    rolePermission.setDeleted(0);
                    rolePermissionMapper.insert(rolePermission);
                }

                // 使用权限同步服务自动分配相关菜单
                int syncedMenus = permissionSyncService.syncMenusForPermissions(roleId, new ArrayList<>(allPermissionIds));

                String message = "分配权限成功";
                if (allPermissionIds.size() > permissionIds.size()) {
                    message += "，已自动包含 " + (allPermissionIds.size() - permissionIds.size()) + " 个依赖权限";
                }
                if (syncedMenus > 0) {
                    message += "，已自动分配 " + syncedMenus + " 个相关菜单";
                }

                return Result.success(message);
            }

            return Result.success("分配权限成功");
        } catch (Exception e) {
            return Result.error("分配权限失败：" + e.getMessage());
        }
    }

    /**
     * 检查并修复角色权限菜单一致性
     */
    public Result<String> checkAndFixConsistency(Long roleId) {
        try {
            String result = permissionSyncService.checkAndFixRolePermissionConsistency(roleId);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("检查权限一致性失败：" + e.getMessage());
        }
    }

    @Override
    public Result<List<Long>> getRolePermissions(Long roleId) {
        try {
            List<RolePermission> rolePermissions = rolePermissionMapper.selectByRoleId(roleId);
            List<Long> permissionIds = rolePermissions.stream()
                    .map(RolePermission::getPermissionId)
                    .collect(Collectors.toList());
            return Result.success(permissionIds);
        } catch (Exception e) {
            return Result.error("查询角色权限失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<String> removeRolePermissions(Long roleId) {
        try {
            rolePermissionMapper.deleteByRoleId(roleId);
            return Result.success("删除角色权限成功");
        } catch (Exception e) {
            return Result.error("删除角色权限失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<String> removePermissionRoles(Long permissionId) {
        try {
            rolePermissionMapper.deleteByPermissionId(permissionId);
            return Result.success("删除权限角色关联成功");
        } catch (Exception e) {
            return Result.error("删除权限角色关联失败：" + e.getMessage());
        }
    }
} 

